package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/26 1:35
 * https://leetcode-cn.com/problems/restore-ip-addresses/
 */
public class RestoreIpAddresses {

    static List<String> result;
    static LinkedList<String> list;

    public static List<String> restoreIpAddresses(String s) {
        result = new ArrayList<>();
        list = new LinkedList<>();
        backTracking(s, 0);
        return result;
    }

    private static void backTracking(String s, int start) {
        if (list.size() == 3 ) {
            //判断第4端ip是否合法
            if (s.length() - start <= 4 && s.length() - start > 0) {
                String substring = s.substring(start, s.length());
                Integer integer = Integer.valueOf(substring);
                if (integer >= 0 && integer <= 255) {
                    if (substring.length() > 1 && substring.charAt(0) == '0') {
                        return;
                    }
                    list.add(substring);
                    String join = String.join(".", list);
                    result.add(join);
                    list.removeLast();
                }
            }
            return;
        }
        for (int i = start; i <= start + 3 && i < s.length(); i++) {
            //考虑"023"这种情况
            String str = s.substring(start, i + 1);
            Integer sub = Integer.valueOf(str);
            if (sub >= 0 && sub <= 255) {
                if (str.length() > 1 && str.charAt(0) == '0') {
                    break;
                }
                list.add(str);
            } else {
                break;
            }
            backTracking(s, i + 1);
            list.removeLast();
        }
    }

    public static void main(String[] args) {
        restoreIpAddresses("25525511135");
    }
}
